package com.sooth.system.menu.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.sooth.common.core.domain.R;
import com.sooth.common.log.annotation.Log;
import com.sooth.common.web.core.BaseController;
import com.sooth.system.menu.service.ISysMenuService;
import com.sooth.system.menu.view.*;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单信息
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {

    private final ISysMenuService menuService;

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public R<List<RouterView>> getRouters() {
        return R.ok(menuService.selectRouterTree());
    }

    /**
     * 获取菜单列表
     */
    @SaCheckPermission("system:menu:query")
    @GetMapping("/list")
    public R<List<SysMenuVo>> list(SysMenuDto menu) {
        List<SysMenuVo> menus = menuService.selectMenuTree(menu);
        return R.ok(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     *
     * @param id 菜单ID
     */
    @SaCheckPermission("system:menu:query")
    @GetMapping(value = "/query")
    public R<SysMenuBo> query(@RequestParam Long id) {
        return R.ok(menuService.selectById(id));
    }

    /**
     * 新增菜单
     */
    @SaCheckPermission("system:menu:add")
    @Log(title = "菜单管理", message = "新增菜单")
    @PostMapping("/add")
    public R<Void> add(@RequestBody SysMenuBo menu) {
        if (menu.getParentId() == null) {
            menu.setParentId(0l);
        }
        return toAjax(menuService.insert(menu));
    }

    /**
     * 修改菜单
     */
    @SaCheckPermission("system:menu:edit")
    @Log(title = "菜单管理", message = "修改菜单")
    @PutMapping("/edit")
    public R<Void> edit(@RequestBody SysMenuBo menu) {
        if (menu.getId().equals(menu.getParentId())) {
            return R.fail("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        return toAjax(menuService.updateWithOrderById(menu));
    }

    /**
     * 删除菜单
     *
     * @param id 菜单ID
     */
    @SaCheckPermission("system:menu:remove")
    @Log(title = "菜单管理", message = "删除菜单")
    @DeleteMapping("/remove")
    public R<Void> remove(@RequestParam Long id) {
        SysMenuDeleted menuDeleted = new SysMenuDeleted();
        menuDeleted.setId(id);
        menuDeleted.setParentId(id);
        return toAjax(menuService.delete(menuDeleted));
    }

}
